from django.db import models
from fuguang.utils.models import BaseModel
from users.models import UserModel
from course.models import CourseModel


# 写完修改  ： 修改优惠劵模型类
class OrdersModel(BaseModel):
    ORDER_STATUS_CHOICES = {
        (0, '未支付'),
        (1, '已支付'),
        (2, '已取消'),
        (3, '已超时'),
    }
    PAY_TYPE_CHOICES = {
        (0, '支付宝'),
        (1, '微信'),
        (2, '余额'),
    }
    total_price = models.DecimalField(max_digits=8, decimal_places=2, default=0, verbose_name='订单总价')
    real_price = models.DecimalField(max_digits=8, decimal_places=2, default=0, verbose_name='实付金额')
    order_number = models.CharField(max_length=64, verbose_name='订单号')
    order_status = models.SmallIntegerField(choices=ORDER_STATUS_CHOICES, default=0, verbose_name='订单状态')
    pay_type = models.SmallIntegerField(choices=PAY_TYPE_CHOICES, default=0, verbose_name='支付方式')
    order_desc = models.TextField(null=True, blank=True, max_length=300, verbose_name='订单描述')
    pay_time = models.DateTimeField(null=True, blank=True, verbose_name='支付时间')
    credit = models.IntegerField(default=0, null=True, blank=True, verbose_name='积分')
    user = models.ForeignKey(to=UserModel, related_name='user_orders', on_delete=models.DO_NOTHING, db_constraint=False, verbose_name='用户')

    # 优惠劵
    def coupon(self):
        # 外键关联查询优惠劵信息
        coupon_related = self.to_coupon.first()
        # 拼接优惠劵信息
        if coupon_related:
            return {
                "id": coupon_related.coupon.id,
                "name": coupon_related.coupon.name,
                "sale": coupon_related.coupon.sale,
                "discount": coupon_related.coupon.discount,
                "condition": coupon_related.coupon.condition
            }
        return {}

    class Meta:
        db_table = 'fg_order'
        verbose_name_plural = '订单记录表'

    def __str__(self):
        return "%s 总价：%s，实付金额：%s" % (self.name, self.total_price, self.real_price)



# 订单详情表
class OrdersDetailModel(BaseModel):
    order = models.ForeignKey(to=OrdersModel, related_name='order_detail', on_delete=models.CASCADE, db_constraint=False, verbose_name='订单')
    course = models.ForeignKey(to=CourseModel, related_name='order_detail', on_delete=models.DO_NOTHING, db_constraint=False, verbose_name='课程')
    price = models.DecimalField(max_digits=8, decimal_places=2, verbose_name='课程原价')
    real_price = models.DecimalField(max_digits=8, decimal_places=2, verbose_name='优惠价格')
    discount_name = models.CharField(max_length=100, default="", verbose_name='优惠类型')

    class Meta:
        db_table = 'fg_order_course'
        verbose_name_plural = '订单详情'

    def __str__(self):
        return self.course.name
